package com.tjvib.view.activity;

import static com.tjvib.Constants.SUCCESS;

import android.Manifest;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;

import com.google.android.material.bottomnavigation.BottomNavigationView;

import androidx.annotation.NonNull;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;

import com.tapadoo.alerter.Alerter;
import com.tjvib.R;
import com.tjvib.base.BaseActivity;
import com.tjvib.common.Callback;
import com.tjvib.presenter.MainPresenter;
import com.tjvib.util.FileUtil;
import com.tjvib.util.LogUtil;
import com.tjvib.util.Manager.AppManager;
import com.tjvib.util.Manager.UserManager;
import com.tjvib.util.SharedPreferencesUtil;
import com.tjvib.util.ToastUtil;
import com.tjvib.util.retrofit.BaseResponse;
import com.tjvib.util.retrofit.RetrofitHelper;
import com.tjvib.view.dialog.HintDialog;
import com.tjvib.view.dialog.InputDialog;
import com.tjvib.view.dialog.LoadingDialog;
import com.tjvib.widget.AndroidScheduler;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import pub.devrel.easypermissions.EasyPermissions;

public class MainActivity extends BaseActivity<MainPresenter> implements EasyPermissions.PermissionCallbacks {

    String[] perms = new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
    int RC_READ_AND_WRITE_EXTERNAL_STORAGE = 50;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        BottomNavigationView navView = findViewById(R.id.nav_view);
        AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
                R.id.navigation_sensor, R.id.navigation_dataset, R.id.navigation_me)
                .build();
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_activity_main);
//        NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
        NavigationUI.setupWithNavController(navView, navController);

        if (presenter.checkTempDataSetExists())
            showStoreTempDataSetDialog();
    }

    @Override
    protected int initLayout() {
        return R.layout.activity_main;
    }

    @Override
    protected boolean initView() {
        if (!EasyPermissions.hasPermissions(this, perms))
            EasyPermissions.requestPermissions(this, "请授予APP读写存储卡权限", RC_READ_AND_WRITE_EXTERNAL_STORAGE, perms);
        return true;
    }

    @Override
    protected boolean initData() {
        return true;
    }

    @Override
    protected MainPresenter genPresenter() {
        return new MainPresenter(this);
    }


    @Override
    protected void onResume() {
        super.onResume();
        LoadingDialog loadingDialog = new LoadingDialog(MainActivity.this);
        loadingDialog.showDialog(MainActivity.this, "正在更新用户信息…");
        RetrofitHelper.getInstance().create().get_info(String.valueOf(UserManager.getInstance().getUserId()))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidScheduler.mainThread())
                .subscribe(new Observer<BaseResponse>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(BaseResponse value) {
                        loadingDialog.dismiss();
                        if (value.getCode() == SUCCESS) {
                            LogUtil.d(value.getMessage() + "\n" + value.getData());
                            String token = UserManager.getInstance().setInfo(String.valueOf(value.getData()));
                            if (!token.isEmpty())
                                SharedPreferencesUtil.saveToken(MainActivity.this, token);
                        } else {
                            LogUtil.e(value.getCode() + "\n" + value.getMessage() + "\n" + value.getData());
                            showErrorDialog(value.getMessage());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        loadingDialog.dismiss();
                        LogUtil.e("get_info" + e.getMessage());
                        showErrorDialogAndExit(e.getMessage() + "\n请重新登录");
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }


    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        // 权限请求成功回调
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        // 权限请求失败回调
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            // 用户拒绝权限并勾选了不再询问
            // 引导用户去设置页面手动开启权限
            ToastUtil.show("请您前往本手机设置手动开启权限");
        }
    }


    private void showStoreTempDataSetDialog() {
        HintDialog hintDialog = new HintDialog(MainActivity.this);
        hintDialog.showDialog(MainActivity.this, "提示",
                "检测到有未成功保存数据，是否保存？", view -> {
                    hintDialog.dismiss();
                    showRenameTempDataDialog();
                },
                view -> {
                    hintDialog.dismiss();
                    FileUtil.deleteDataSetTempFile(MainActivity.this);
                });
    }


    private void showRenameTempDataDialog() {
        String dataSetType = FileUtil.getTempDataSetType(MainActivity.this);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd_HHmmss");
        String localTime = format.format(new Date(System.currentTimeMillis()));
        String defaultDataSetName = getString(R.string.default_data_set_name, dataSetType, localTime);

        InputDialog inputDialog = new InputDialog(MainActivity.this);
        dialogs.add(inputDialog);
        inputDialog.showDialog(MainActivity.this, "请输入数据集名称", "",
                "默认：" + defaultDataSetName,
                v -> {
                    String tableName = inputDialog.getEtCon().getText().toString().trim();
                    if (tableName.isEmpty()) {
                        tableName = defaultDataSetName;
                    }

                    String[] numbers = new String[]{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"};
                    for (String number : numbers) {
                        if (tableName.startsWith(number)) {
                            ToastUtil.show("不能以数字开头");
                            return;
                        }
                    }
                    inputDialog.dismiss();
                    dialogs.remove(inputDialog);

                    ProgressDialog progressDialog = new ProgressDialog(this);
                    progressDialog.setCanceledOnTouchOutside(false);
                    progressDialog.setMessage("正在上传中");
                    progressDialog.show();
                    presenter.storeTempDataSet(tableName, new Callback() {
                        @Override
                        public void onSuccess(String message, String data) {
                            progressDialog.dismiss();
                            LogUtil.d("showRenameTempDataDialog onSuccess");
                            showHintDialog(message);
                        }

                        @Override
                        public void onFail(String message, String data) {
                            progressDialog.dismiss();
                            LogUtil.e("showRenameTempDataDialog onFail : " + message);
                            showErrorDialog(message);
                        }

                        @Override
                        public void onError(String message, String data) {
                            progressDialog.dismiss();
                            LogUtil.e("showRenameTempDataDialog onError : " + message);
                            showErrorDialog(message);
                        }
                    });
                },
                v -> showDiscardDataDialog());
    }

    private void showDiscardDataDialog() {
        Dialog dialog = new android.app.AlertDialog.Builder(this)
                .setTitle("警告")
                .setMessage("将丢弃已记录数据，是否继续？")
                .setPositiveButton("确定", (dialog1, which) -> {
                    presenter.discardTempDataSet();
                    dialog1.dismiss();
                    dialogs.remove(dialog1);
                    for (Dialog d : dialogs) {
                        d.dismiss();
                    }
                    dialogs.clear();
                })
                .setNegativeButton("取消", (dialogInterface, i) -> showStoreTempDataSetDialog())
                .create();
        dialogs.add(dialog);
        dialog.show();
    }

}